package cn.ysym.tcsy;

import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import cn.ysym.dao.ProductDao;
import cn.ysym.dao.SettingDao;

import butterknife.ButterKnife;
import cn.ysym.model.Product;
import cn.ysym.model.Setting;
import cn.ysym.util.CommonUtil;
import cn.ysym.util.HttpUtil;
import cn.ysym.util.VibratorUtil;

public class OnlineCancelStockActivity extends AppCompatActivity {

    @BindView(R.id.lvData)
    ListView lvData;
    @BindView(R.id.lvBatch)
    ListView lvBatch;
    private boolean taskDoing = false;
    private SettingDao settingDao;
    private ProductDao productDao;
    private ProgressBar progressBar;
    private EditText etProduct;
    private ListView lvProduct;
    private EditText etCode;
    private TextView tvResult;
    private Button bShippingFinish;
    private String productId;   //选中产品id

    private UpDataTask upDataTask;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_online_stock);
        ButterKnife.bind(this); //绑定butterKnife插件
        setTitle("在线退库");

        settingDao = new SettingDao(this);
        productDao = new ProductDao(this);

        progressBar = (ProgressBar) findViewById(R.id.progressBarOnline);
        etProduct = (EditText) findViewById(R.id.etProduct);
        lvProduct = (ListView) findViewById(R.id.lvProduct);
        lvProduct.setVerticalScrollBarEnabled(true);
        tvResult = findViewById(R.id.tvResult);


        etProduct.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    ArrayAdapter<String> productAdapter = new ArrayAdapter<String>(OnlineCancelStockActivity.this, R.layout.list_view);
                    List<Product> ps = productDao.query("");
                    for (Product p : ps) {
                        productAdapter.add(CommonUtil.formatStr(p.getProductName()));
                    }
                    lvProduct.setAdapter(productAdapter);
                    lvProduct.setVisibility(View.VISIBLE);
                } else {
                    lvProduct.setVisibility(View.GONE);
                }
            }
        });

        etProduct.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                ArrayAdapter<String> productAdapter = new ArrayAdapter<String>(OnlineCancelStockActivity.this, R.layout.list_view);
                List<Product> ps = productDao.query(s.toString());
                for (Product p : ps) {
                    productAdapter.add(CommonUtil.formatStr(p.getProductName()));
                }
                lvProduct.setAdapter(productAdapter);
                lvProduct.setVisibility(View.VISIBLE);
            }
        });

        lvProduct.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String text = parent.getAdapter().getItem(position).toString();
                etProduct.setText(text);
                lvProduct.setVisibility(View.GONE);
                etCode.requestFocus();
            }
        });


        etCode = (EditText) findViewById(R.id.etCode);
        etCode.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
                    if (upDataTask == null) {
                        String code = CommonUtil.cleanCode(etCode.getText().toString());
                        etCode.setText(code);
                        progressBar.setVisibility(View.VISIBLE);
                        String productId = etProduct.getText().toString();
                        productId = productId.replace("\n", "");
                        int tIndex = productId.indexOf(" ");
                        if (tIndex > 0) productId = productId.substring(0, tIndex);
                        upDataTask = new UpDataTask(productId,code);
                        upDataTask.execute((Void) null);
                    }
                }
                return false;
            }
        });

        bShippingFinish = findViewById(R.id.bShippingFinish);
        bShippingFinish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //弹出退出确认框
                new AlertDialog.Builder(OnlineCancelStockActivity.this)
                        .setTitle("系统提示")
                        .setMessage("确认退库完成？")
                        .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                taskDoing = true;
                                progressBar.setVisibility(View.VISIBLE);
                                String productId = etProduct.getText().toString();
                                productId = productId.replace("\n", "");
                                int tIndex = productId.indexOf(" ");
                                if (tIndex > 0) productId = productId.substring(0, tIndex);
                                CancelStockFinishTask task = new CancelStockFinishTask(productId);
                                task.execute((Void) null);
                                String code = CommonUtil.cleanCode(etCode.getText().toString());
                                etCode.setText(code);
                                GetCancelStockDetailTask task1 = new GetCancelStockDetailTask(productId);
                                task1.execute((Void) null);
                            }
                        }).setNegativeButton("取消",null).show();
            }
        });


    }

    public class UpDataTask extends AsyncTask<Void, Void, String> {
        private String productId;
        private String code;
        private String message = "对不起，服务异常！";

        public UpDataTask(String productId, String code) {
            this.productId = productId;
            this.code = code;
        }

        @Override
        protected String doInBackground(Void... params) {
            JSONObject req = new JSONObject();
            try {
                Setting userName = settingDao.query("userName");
                Setting sessionKey = settingDao.query("sessionKey");
                req.put("version", "2.3.180801.a.main");
                req.put("account", userName.getSettingValue());
                req.put("productId", productId);
                req.put("bigCode", "");
                req.put("code", code);
                req.put("sign", HttpUtil.genSign(req, sessionKey.getSettingValue()));
                String retStr = HttpUtil.postJson("upCancelStockDataNew.sdo", req.toString());
                return retStr;
            } catch (Exception e) {
                Log.d("zqfw", e.getMessage());
            }

            return null;
        }

        @Override
        protected void onPostExecute(final String retStr) {
            upDataTask = null;
            taskDoing = false;
            progressBar.setVisibility(View.GONE);
            if (retStr != null) {
                try {
                    JSONObject retJson = new JSONObject(retStr);
                    if (retJson.getInt("result") == 2) {
                        //更新显示列表
                        taskDoing = true;
                        progressBar.setVisibility(View.VISIBLE);
                        String productId = etProduct.getText().toString();
                        productId = productId.replace("\n", "");
                        int tIndex = productId.indexOf(" ");
                        if (tIndex > 0) productId = productId.substring(0, tIndex);
                        GetCancelStockDetailTask task = new GetCancelStockDetailTask(productId);
                        task.execute((Void) null);
                        message = retJson.getString("message");
                        Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
                        tvResult.setText(message);
                    } else {
                        CommonUtil.playSound(OnlineCancelStockActivity.this);
                        message = retJson.getString("message");
                        VibratorUtil.vibrate(getApplicationContext(), VibratorUtil.milliSeconds);
                        Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
                        tvResult.setText(message);
                    }
                } catch (JSONException e) {
                    Log.d("zqfw", e.getMessage());
                }
                etCode.setText("");
                etCode.requestFocus();
            }
        }
    }

    public class GetCancelStockDetailTask extends AsyncTask<Void, Void, String> {
        private String productId;
        private String message = "对不起，服务异常！";

        public GetCancelStockDetailTask(String productId) {
            this.productId = productId;
        }

        @Override
        protected String doInBackground(Void... params) {
            JSONObject req = new JSONObject();
            try {
                Setting userName = settingDao.query("userName");
                Setting sessionKey = settingDao.query("sessionKey");
                req.put("version", CommonUtil.getSoftVersion());
                req.put("account", userName.getSettingValue());
                req.put("productId", productId);
                req.put("sign", HttpUtil.genSign(req, sessionKey.getSettingValue()));
                String retStr = HttpUtil.postJson("getCancelStockDetail.sdo", req.toString());
                return retStr;
            } catch (Exception e) {
                message = e.getMessage();
            }
            return null;
        }

        @Override
        protected void onPostExecute(final String retStr) {
            taskDoing = false;
            progressBar.setVisibility(View.GONE);
            if (retStr != null) {
                try {
                    JSONObject retJson = new JSONObject(retStr);
                    JSONArray data = retJson.getJSONArray("data");
                    List<HashMap<String, Object>> listData = new ArrayList<>();
                    for (int i = 0; i < data.length(); i++) {
                        JSONObject item = data.getJSONObject(i);
                        HashMap<String, Object> oneData = new HashMap<>();
                        String productName = item.getString("productName");
                        String bigNum = item.getString("bigNumber");
                        String midNum = item.getString("middleNumber");
                        String sanNum = item.getString("sanNumber");
                        oneData.put("productName", productName);
                        oneData.put("bigNumber", bigNum);
                        oneData.put("middleNumber", midNum);
                        oneData.put("sanNumber", sanNum);
                        listData.add(oneData);
                    }
                    SimpleAdapter adapter = new SimpleAdapter(OnlineCancelStockActivity.this, listData, R.layout.shipping_data_item,
                            new String[]{"productName", "bigNumber", "middleNumber", "sanNumber"}, new int[]{R.id.tvProductId, R.id.tvProductName, R.id.tvSendNum, R.id.tvSentNum});
                    lvData.setAdapter(adapter);

                    if (retJson.getInt("status") != 200) {
                        message = retJson.getString("message");
                        VibratorUtil.vibrate(getApplicationContext(), VibratorUtil.milliSeconds);
                        Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
                        tvResult.setText(message);
                    }else{
                        Toast.makeText(getApplicationContext(), "成功", Toast.LENGTH_SHORT).show();
                        tvResult.setText("成功");
                    }
                } catch (JSONException e) {
                    message = e.getMessage();
                }
            } else {
                VibratorUtil.vibrate(getApplicationContext(), VibratorUtil.milliSeconds);
                Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
            }
        }
    }

    public class CancelStockFinishTask extends AsyncTask<Void,Void,String>{

        private String productId;
        private String message = "对不起，服务异常";

        public CancelStockFinishTask(String productId){
            this.productId = productId;
        }

        @Override
        protected String doInBackground(Void... params) {
            JSONObject req = new JSONObject();
            try {
                Setting userName = settingDao.query("userName");
                Setting sessionKey = settingDao.query("sessionKey");
                req.put("version", CommonUtil.getSoftVersion());
                req.put("account", userName.getSettingValue());
                req.put("productId", productId);
                req.put("bigCode", "");
                req.put("sign", HttpUtil.genSign(req, sessionKey.getSettingValue()));
                String retStr = HttpUtil.postJson("cancelStockFinish.sdo", req.toString());
                return retStr;
            }catch (Exception e){
                message = e.getMessage();
            }
            return null;
        }

        @Override
        protected void onPostExecute(final String retStr) {
            taskDoing = false;
            progressBar.setVisibility(View.GONE);
            if(retStr != null){
                try {
                    JSONObject retJson = new JSONObject(retStr);
                    if (retJson.getInt("status") == 200) {
                        Toast.makeText(getApplicationContext(), "成功", Toast.LENGTH_SHORT).show();
                        tvResult.setText("成功");
                    } else {
                        CommonUtil.playSound(OnlineCancelStockActivity.this);
                        message = retJson.getString("message");
                        VibratorUtil.vibrate(getApplicationContext(), VibratorUtil.milliSeconds);
                        Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
                        tvResult.setText(message);
                    }
                } catch (JSONException e) {
                    message = e.getMessage();
                }
            }else {
                CommonUtil.playSound(OnlineCancelStockActivity.this);
                tvResult.setText(message);
            }
        }
    }
}
